<template>
    <div class="login-container">
        <canvas id="canvas" class="dot-bg" width="100%" height="100%"></canvas>
        <div class="login-card" v-if="state==='login'">
            <el-form class="login-form">
                <div class="title-container">
                    <h1 class="title">{{ msg_login }}</h1>
                </div>
                <el-form-item prop="name">
                    <el-input
                            ref="username"
                            v-model="name"
                            placeholder="Username"
                            name="username"
                            type="text"
                            prefix-icon="el-icon-user"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="password">
                    <el-input
                            ref="password"
                            v-model="password"
                            placeholder="Password"
                            name="password"
                            type="password"
                            prefix-icon="el-icon-key"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="code">
                    <el-input class="input-with-suffix"
                              ref="code"
                              v-model="code"
                              placeholder="验证码"
                              name="code"
                              type="code"
                              prefix-icon="el-icon-key"
                              @change="my_login"
                    >
                    </el-input>
                    <el-image class="suffix" id="image" @click="fresh"
                              :src="imageSrc"/>
                </el-form-item>
                <div class="login-button-wrapper">
                    <el-button type="primary"
                               class="login-button"
                               @click.native.prevent="my_login">
                        Log in
                    </el-button>
                    <div class="link-wrapper">
                        <a class="link" @click="gotoRegister">没有账号？现在注册</a>
                        <a class="link" @click="gotoForgetPassword">忘记密码？</a>
                    </div>
                </div>
            </el-form>
        </div>
        <div class="login-card" v-if="state==='register'">
            <el-form class="login-form">
                <div class="title-container">
                    <i class="el-icon-back back-to-login" @click="backToLogin"></i>
                    <h1 class="title">{{ msg_register }}</h1>
                </div>
                <el-form-item prop="name">
                    <el-input
                            ref="username"
                            v-model="name"
                            placeholder="用户名"
                            name="username"
                            type="text"
                            prefix-icon="el-icon-user" aria-required="true"
                    >
                        <el-select slot="append"
                                   style="width: 100px"
                                   placeholder="性别"
                                   v-model="gender">
                            <el-option v-for="item in optionsGender"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value">
                            </el-option>
                        </el-select>
                    </el-input>
                </el-form-item>
                <el-form-item prop="passwordR">
                    <el-input
                            ref="passwordR"
                            v-model="passwordR"
                            placeholder="设置密码"
                            name="passwordR"
                            type="passwordR"
                            prefix-icon="el-icon-key" aria-required="true"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="passwordRR">
                    <el-input
                            ref="passwordRR"
                            v-model="passwordRR"
                            placeholder="再次确认密码"
                            name="passwordRR"
                            type="passwordRR"
                            prefix-icon="el-icon-key" aria-required="true"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="email">
                    <el-input
                            ref="email"
                            v-model="email"
                            placeholder="邮箱"
                            name="email"
                            type="email"
                            prefix-icon="el-icon-message" aria-required="true"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="mailCode">
                    <el-input
                            ref="mailCode"
                            v-model="mailCode"
                            placeholder="邮箱验证码"
                            name="mailCode"
                            type="mailCode"
                            prefix-icon="el-icon-key" aria-required="true"
                    >
                        <el-button slot="append"
                                   @click="sendEmailCode"
                        >获取验证码
                        </el-button>
                    </el-input>
                </el-form-item>
                <el-button type="primary" class="login-button" @click.native.prevent="my_register">Sign in
                </el-button>
            </el-form>
        </div>
        <div class="login-card" v-if="state==='forgetPassword'">
            <el-form class="login-form">
                <div class="title-container">
                    <i class="el-icon-back back-to-login" @click="backToLogin"></i>
                    <h1 class="title">{{ msg_forgetPassword }}</h1>
                </div>
                <el-form-item prop="name">
                    <el-input
                            ref="username"
                            v-model="name"
                            placeholder="Username"
                            name="username"
                            type="text"
                            prefix-icon="el-icon-user" aria-required="true"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="email">
                    <el-input
                            ref="email"
                            v-model="email"
                            placeholder="邮箱"
                            name="email"
                            type="email"
                            prefix-icon="el-icon-message"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="mailCode">
                    <el-input
                            ref="mailCode"
                            v-model="mailCode"
                            placeholder="邮箱验证码"
                            name="mailCode"
                            type="mailCode"
                            prefix-icon="el-icon-key"
                    >
                        <el-button slot="append" @click="sendEmailCodeL">获取验证码</el-button>
                    </el-input>
                </el-form-item>
                <el-form-item prop="passwordF">
                    <el-input
                            ref="passwordF"
                            v-model="passwordF"
                            placeholder="设置密码"
                            name="passwordF"
                            type="passwordF"
                            prefix-icon="el-icon-key"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="passwordFR">
                    <el-input
                            ref="passwordFR"
                            v-model="passwordFR"
                            placeholder="再次确认密码"
                            name="passwordFR"
                            type="passwordFR"
                            prefix-icon="el-icon-key"
                    ></el-input>
                </el-form-item>
                <el-button type="primary" class="login-button" @click.native.prevent="my_findPassword">Confirm
                </el-button>
            </el-form>
        </div>
    </div>
</template>

<script>
    import {mapActions} from "vuex";

    export default {
        name: "login",
        inject: ["reload1"],
        data: function () {
            return {
                mode: "login",
                name: "",
                password: "",
                content: "",
                code: "",
                url: "",
                email: "",
                mailCode: "",
                gender: "",
                passwordR: "",
                passwordRR: "",
                passwordF: "",
                passwordFR: "",
                msg_login: "KG-创建你的知识图谱",
                msg_register: "KG-注册",
                msg_forgetPassword: "KG-找回密码",
                login_data: {},
                imageSrc: "http://101.200.57.150:8001/get_one_captcha",
                optionsGender: [
                    {
                        value: 0,
                        label: "男",
                    },
                    {
                        value: 1,
                        label: "女",
                    }
                ],
                state: "login"
            };
        },
        mounted() {
            this.init_dot_bg();
            this.fresh();
        },
        methods: {
            ...mapActions([
                "login",
                "register",
                "sendMailCode",
                "sendMailCodeL",
                "findPassword",
                "getOneCaptcha"
            ]),
            fresh: function () {
                this.getOneCaptcha().then(res => {
                    var img = document.getElementById("image");
                    const myBlob = new window.Blob([res], {type: "image/jpeg"});
                    const qrUrl = window.URL.createObjectURL(myBlob);
                    img.src = qrUrl;
                    img.onload = function () {
                        window.URL.revokeObjectURL(qrUrl);
                    };
                });
            },
            my_login: function () {
                let loginDto = {
                    code: this.code.toString(),
                    password: this.password.toString(),
                    username: this.name.toString()
                };
                this.login(loginDto).then(result => {
                    if (result.code === 200) {
                        this.$router.push({
                            path: "/home/homePage",
                        }).catch(err => {

                        });
                        this.$cookies.set("userId", result.data.id);
                    } else if (result.code === 500) {
                        this.$message.error("服务器异常，请稍后重试");
                    } else if (result.code === 400) {
                        this.$message.error("验证码错误");
                    } else {
                        this.$message.error("服务器异常，请稍后重试");
                    }
                });

            },
            my_register: function () {
                if (this.passwordR !== this.passwordRR) {
                    this.$message.error("两次密码输入不一致");
                }
                let data = {
                    email: this.email,
                    gender: this.gender,
                    mailCode: this.mailCode,
                    name: this.name,
                    password: this.passwordR
                };
                this.register(data).then(res => {
                    if (res.code === 200) {
                        this.$message.success("注册成功");
                        this.state = "login";
                    }
                });

            },
            my_findPassword: function () {
                if (this.passwordF !== this.passwordFR) {
                    this.$message.error("两次密码输入不一致");
                }
                let data = {
                    mailCode: this.mailCode,
                    name: this.name,
                    newPassword: this.passwordF
                };
                this.findPassword(data).then(res => {
                    if (res.code === 200) {
                        this.$message.success("修改密码成功");
                        this.state = "login";
                    }
                });
            },
            gotoRegister: function () {
                this.state = "register";
            },
            gotoForgetPassword: function () {
                this.state = "forgetPassword";
            },
            sendEmailCode: function () {
                this.sendMailCode({mail: this.email}).then(res => {
                    if (res.code === 200) {
                        this.$message.success("验证码发送成功！");
                    } else {
                        this.$message.success("邮箱有误！");
                    }
                });
            },
            sendEmailCodeL: function () {
                this.sendMailCodeL({mail: this.email}).then(res => {
                    if (res.code === 200) {
                        this.$message.success("验证码发送成功！");
                    } else {
                        this.$message.success("邮箱有误！");
                    }
                });
            },
            init_dot_bg: function () {
                class Circle {
                    //创建对象
                    //以一个圆为对象
                    //设置随机的 x，y坐标，r半径，_mx，_my移动的距离
                    //this.r是创建圆的半径，参数越大半径越大
                    //this._mx,this._my是移动的距离，参数越大移动
                    constructor(x, y) {
                        this.x = x;
                        this.y = y;
                        this.r = Math.random() * 10;
                        this._mx = Math.random();
                        this._my = Math.random();

                    }

                    //canvas 画圆和画直线
                    //画圆就是正常的用canvas画一个圆
                    //画直线是两个圆连线，为了避免直线过多，给圆圈距离设置了一个值，距离很远的圆圈，就不做连线处理
                    drawCircle(ctx) {
                        ctx.beginPath();
                        //arc() 方法使用一个中心点和半径，为一个画布的当前子路径添加一条弧。
                        ctx.arc(this.x, this.y, this.r, 0, 360);
                        ctx.closePath();
                        ctx.fillStyle = "rgba(204, 204, 204, 0.3)";
                        ctx.fill();
                    }

                    drawLine(ctx, _circle) {
                        let dx = this.x - _circle.x;
                        let dy = this.y - _circle.y;
                        let d = Math.sqrt(dx * dx + dy * dy);
                        if (d < 150) {
                            ctx.beginPath();
                            //开始一条路径，移动到位置 this.x,this.y。创建到达位置 _circle.x,_circle.y 的一条线：
                            ctx.moveTo(this.x, this.y);   //起始点
                            ctx.lineTo(_circle.x, _circle.y);   //终点
                            ctx.closePath();
                            ctx.strokeStyle = "rgba(204, 204, 204, 0.3)";
                            ctx.stroke();
                        }
                    }

                    // 圆圈移动
                    // 圆圈移动的距离必须在屏幕范围内
                    move(w, h) {
                        this._mx = (this.x < w && this.x > 0) ? this._mx : (-this._mx);
                        this._my = (this.y < h && this.y > 0) ? this._my : (-this._my);
                        this.x += this._mx / 2;
                        this.y += this._my / 2;
                    }
                }

                //鼠标点画圆闪烁变动
                class currentCircle extends Circle {
                    constructor(x, y) {
                        super(x, y);
                    }

                    drawCircle(ctx) {
                        ctx.beginPath();
                        //注释内容为鼠标焦点的地方圆圈半径变化
                        //this.r = (this.r < 14 && this.r > 1) ? this.r + (Math.random() * 2 - 1) : 2;
                        this.r = 4;
                        ctx.arc(this.x, this.y, this.r, 0, 360);
                        ctx.closePath();
                        //ctx.fillStyle = 'rgba(0,0,0,' + (parseInt(Math.random() * 100) / 100) + ')'
                        ctx.fillStyle = "rgba(243,255,172,0.6)";
                        ctx.fill();

                    }
                }

                //更新页面用requestAnimationFrame替代setTimeout
                window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;

                let canvas = document.getElementById("canvas");
                let ctx = canvas.getContext("2d");
                let w = canvas.width = canvas.offsetWidth;
                let h = canvas.height = canvas.offsetHeight;
                let circles = [];
                let current_circle = new currentCircle(0, 0);

                let draw = function () {
                    ctx.clearRect(0, 0, w, h);
                    for (let i = 0; i < circles.length; i++) {
                        circles[i].move(w, h);
                        circles[i].drawCircle(ctx);
                        for (let j = i + 1; j < circles.length; j++) {
                            circles[i].drawLine(ctx, circles[j]);
                        }
                    }
                    if (current_circle.x) {
                        current_circle.drawCircle(ctx);
                        for (var k = 1; k < circles.length; k++) {
                            current_circle.drawLine(ctx, circles[k]);
                        }
                    }
                    requestAnimationFrame(draw);
                };

                let init = function (num) {
                    for (let i = 0; i < num; i++) {
                        circles.push(new Circle(Math.random() * w, Math.random() * h));
                    }
                    draw();
                };

                window.addEventListener("load", init(60));
                window.onmousemove = function (e) {
                    e = e || window.event;
                    current_circle.x = e.clientX;
                    current_circle.y = e.clientY;
                };
                window.onmouseout = function () {
                    current_circle.x = null;
                    current_circle.y = null;

                };

            },
            backToLogin: function () {
                this.state = "login";
            }
        }
    };
</script>


<style scoped>
    @import "../assets/styles/login.css";
</style>
